package com.bestcem.xm.user.grpc.client;

import com.bestcem.bp.grpc.v1.base.Code;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.grpc.v1.services.*;
import com.bestcem.xm.user.grpc.client.dto.WechatUserDetailDTO;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import zhongyan.xm.base.v1.Base;

import java.util.Objects;

/**
 * 微信/企业微信相关grpc接口
 *
 * @author Linzhijian <zhijian.lin@idiaoyan.com>
 * @version v1.0
 * @date 2022/5/12 15:50
 */
@Slf4j
@Service(value = "userUserWechatWorkGrpcService")
public class UserWechatWorkGrpcService {

    @GrpcClient(GrpcClientNames.XM)
    private BpWechatWorkServiceGrpc.BpWechatWorkServiceBlockingStub stub;

    /**
     * 获取用户凭证
     * <p>
     * wxwork_mini_session:{session_id}
     *
     * @param sessionId
     * @return com.bestcem.xm.user.grpc.client.dto.WechatUserDetailDTO
     * @author Linzhijian <zhijian.lin@idiaoyan.com>
     * @date 2022/05/13 09:34
     */
    public WechatUserDetailDTO getWxworkUserDetail(String sessionId, String prefix) {
        WechatUserDetailDTO detailDTO = new WechatUserDetailDTO();
        GetWxworkUserDetailResponse response = stub.getWxworkUserDetail(GetWxworkUserDetailRequest.newBuilder().setSessionId(sessionId).setPrefix(prefix).build());
        if (Objects.isNull(response)) {
            return null;
        }
        detailDTO.setCorpid(response.getCorpid());
        detailDTO.setQyWxOpenUserid(response.getOpenUserid());
        detailDTO.setUserId(response.getUserid());
        detailDTO.setName(response.getName());
        detailDTO.setManager(response.getManager());
        detailDTO.setEmail(response.getEmail());
        detailDTO.setPhone(response.getMobile());
        detailDTO.setWxNickname(response.getWxNickname());
        return detailDTO;
    }


    /**
     * 缓存企业微信数据
     * wxwork_mini_session
     *
     * @param sessionId
     * @param detailDTO
     * @return void
     * @author Linzhijian <zhijian.lin@idiaoyan.com>
     * @date 2022/05/13 11:59
     */
    public void cacheWxworkSessionInfo(String sessionId, WechatUserDetailDTO detailDTO) {
        CacheWxworkSessionInfoRequest.Builder builder = CacheWxworkSessionInfoRequest.newBuilder();
        builder.setSessionId(sessionId);
        builder.setCorpid(detailDTO.getCorpid());
        builder.setOpenUserid(detailDTO.getQyWxOpenUserid());
        builder.setName(detailDTO.getName());
        builder.setManager(detailDTO.getManager());
        builder.setEmail(detailDTO.getEmail());
        builder.setMobile(detailDTO.getPhone());
        // 是否需要判断需要确认 会空指针
        if (StringUtils.isNotBlank(detailDTO.getWxNickname())) {
            builder.setWxNickname(detailDTO.getWxNickname());
        }
        CacheWxworkSessionInfoResponse response = stub.cacheWxworkSessionInfo(builder.build());
        Integer status = response.getStatus().getCodeValue();

        if (!status.equals(Code.OK.getNumber())) {
            log.error(String.format("[USER] grpc cacheWxworkSessionInfo error sessionId = %s ", sessionId));
        }
    }

    /**
     * 企业微信中打开微信小程序 login 后获取并存储用户凭证
     * apps_mysql/auth/handlers.py:901
     *
     * @param code
     * @return com.bestcem.xm.util.ServiceResult<java.lang.String>
     * @author Linzhijian <zhijian.lin@idiaoyan.com>
     * @date 2022/06/02 16:53
     */
    public ServiceResult<String> wxWorkCodeView(String code) {
        WxworkCodeViewResponse response = stub.wxworkCodeView(WxworkCodeViewRequest.newBuilder().setCode(code).build());
        Integer status = response.getStatus().getCodeValue();
        if (!status.equals(Code.OK.getNumber())) {
            log.error(String.format("[USER] grpc wxWorkCodeView error code = %s ", code));
            return ServiceResult.fail("");
        }
        return ServiceResult.success(response.getSessionId());
    }


    /**
     * 根据 corpId 清除企微公司缓存信息
     *
     * @param corpId 公司id
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2022/7/18 16:22
     */
    public void clearWxworkCorpTokenCache(String corpId) {
        if (Objects.isNull(corpId)) {
            return;
        }
        ClearWxworkCorpTokenCacheRequest.Builder builder = ClearWxworkCorpTokenCacheRequest.newBuilder();
        builder.setCorpId(corpId);
        try {
            ClearWxworkCorpTokenCacheResponse response =
                    stub.clearWxworkCorpTokenCache(builder.build());
            if (Objects.isNull(response) || Base.Code.ERROR.equals(response.getStatus().getCode())) {
                log.error("[User] WxWork clearWxworkCorpTokenCache {} Error; ErrorMsg: {}", corpId, response);
            }
        } catch (Exception e) {
            log.error("[User] WxWork clearWxworkCorpTokenCache {} Error;", corpId, e);
        }
    }


    /**
     * 根据 corpId 解绑企微公司绑定
     *
     * @param corpId 公司id
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2022/7/18 17:24
     */
    public boolean unbindWxworkCorp(String corpId) {
        if (Objects.isNull(corpId)) {
            return false;
        }
        UnbindWxworkCorpRequest.Builder builder = UnbindWxworkCorpRequest.newBuilder();
        builder.setCorpId(corpId);
        try {
            UnbindWxworkCorpResponse response =
                    stub.unbindWxworkCorp(builder.build());
            if (Objects.isNull(response) || Base.Code.ERROR.equals(response.getStatus().getCode())) {
                log.error("[User] WxWork unbindWxworkCorp {} Error; ErrorMsg: {}", corpId, response);
                return false;
            }
            return true;
        } catch (Exception e) {
            log.error("[User] WxWork unbindWxworkCorp {} Error;", corpId, e);
            return false;
        }
    }
}
